// https://data.vatsim.net/v3/vatsim-data.json
import { error } from "@tauri-apps/plugin-log";
import { fetch } from "@tauri-apps/plugin-http";
import { RenderData } from "../classes/RadarRenderData";
import { RadarScreen } from "../RadarCanvasDrawer";

let dataRefreshing: boolean = false;
let dataFetchTimer: number = 0;
let intervalValid: boolean = false;

export async function getVatsimData(): Promise<void> {
    const lastRefreshTime = new Date(RenderData.vatsimData.general.update_timestamp);
    // prevent duplicate function call, and set minimal refresh interval to 15 seconds
    if (dataRefreshing || Date.now() - lastRefreshTime.getTime() < 15000) {
        return;
    }
    dataRefreshing = true;
    try {
        const res = await fetch("https://data.vatsim.net/v3/vatsim-data.json");
        RenderData.vatsimData = await res.json();
    } catch (e) {
        error(`Error getVatsimData: ${e}`);
    }
    dataRefreshing = false;
}

export function startVatsimDataFetchInterval() {
    intervalValid = true;
    clearInterval(dataFetchTimer);
    dataFetchTimer = setInterval(() => {
        getVatsimData().then(() => RadarScreen.draw());
    }, 15000);
    getVatsimData().then(() => RadarScreen.draw());
}

export function stopVatsimDataFetchInterval() {
    clearInterval(dataFetchTimer);
    intervalValid = false;
}

export function isFetchingVatsimData() {
    return intervalValid;
}